/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatroom.com.clientserver;

import chatroom.com.frame.AdminFrame;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ChatServer {

    private final static int port = 6000;
    private static ServerSocket server;
    private static Vector<Socket> connections;// 连接
    private static Vector<ServerThread> clients;
    private static int count = 0;
    private static boolean flag = true;

    /**
     * 功能：发送消息给所有的人
     *
     * @param msg
     */
    public static void sendMsgToAll(String msg) {
        if (connections != null) {
            for (Socket socket : connections) {
                try {
                    PrintWriter pw = new PrintWriter(socket.getOutputStream());
                    pw.println(msg);
                    pw.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("服务器发送给所有人的消息：" + msg);
    }

    /**
     * 功能：发送消息给某一个人
     *
     * @param msg
     * @param userName
     */
    public static boolean sendMsgToOne(String userName, String msg) {
        if (getClients() != null) {
            for (ServerThread sh : getClients()) {
                if (sh.getName().equals(userName)) {
                    try {
                        PrintWriter pw = new PrintWriter(sh.getSocket().getOutputStream());
                        pw.println(msg);
                        pw.flush();
                        return true; // 返回值为真，找到了这个人可以进行聊天
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                }
            }
        }
        return false;// 没有找到这个人，应该是此人已经退出了聊天室
    }

    /**
     * 功能：新增一个连接
     *
     * @param socket
     * @param cp
     */
    public static void addConnection(Socket socket, ServerThread cp) {
        if (connections == null) {
            connections = new Vector<Socket>();
        }
        connections.addElement(socket);
        if (getClients() == null) {
            setClients(new Vector<ServerThread>());
        }
        getClients().addElement(cp);
    }

    /**
     * 功能：通过名称删除一个链接，也就是实现踢人
     *
     * @param name
     */
    public static void deleteConnectionByName(String userName) {
        for (ServerThread sh : getClients()) {
            if (sh.getName().equals(userName)) {

                deleteConnection(sh.getSocket(), sh);
                AdminFrame.deleteOneUser(sh.getIndex(), sh.getName());
            }
        }
    }

    public static String getIpAddressByNick(String userName) {
        String str = null;
         for (ServerThread sh : getClients()) {
            if (sh.getName().equals(userName)) {
                str = sh.getIpAddress();
            }
        }
        return str;
    }

    /**
     * 功能：删除一个连接
     *
     * @param socket
     * @param sh
     */
    public static void deleteConnection(Socket socket, ServerThread sh) {
        if (getConnections() != null) {
            getConnections().removeElement(socket);
            try {
                socket.close();
            } catch (IOException ex) {
                Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (getClients() != null) {
            getClients().removeElement(sh);
        }
    }

    /**
     * 功能：删除所有的连接
     */
    public static void deleteAllConnection() {
        if (getClients() != null) {
            for (ServerThread sh : getClients()) {
                deleteConnection(sh.getSocket(), sh);
            }
        }
    }

    /**
     * 功能：停止服务器
     */
    public static void stopServer() {
        if (getServer() == null) {
            System.err.print("服务器已经关闭，请重新启动");
        } else {
            try {
                deleteAllConnection();
                flag = false;
                server.close();
                server = null;
                System.err.print("服务器关闭成功!");
            } catch (IOException ex) {
                ex.printStackTrace();
                Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * 功能：启动服务器
     */
    public static void startServer() {
        try {
            server = new ServerSocket(port);
            flag = true;
            System.err.print("服务器已经启动，正在监听用户线程.....");
        } catch (Exception e) {
            System.out.println("异常");
            System.err.println(e);

        }
        while (flag) { // 死循环
            Socket socket = null;
            try {
                socket = server.accept();
                System.err.println(socket.getInetAddress().toString());
                ServerThread cp = new ServerThread(socket, socket.getInetAddress().toString().split("/")[1]); // 启动一个用户线程
                cp.setIpAddress(socket.getInetAddress().toString().split("/")[1]);
                System.out.println("新进入一个用户");
                cp.setIndex(count + 1);
                Thread ct = new Thread(cp);
                ct.start();
                addConnection(socket, cp);
                count++;

            } catch (IOException e) {
                System.err.println(e);


                try {
                    socket.close();
                } catch (IOException e1) {

                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            server = new ServerSocket(port);
            System.err.println("服务器已经启动，正在监听...");

        } catch (IOException e) {
            System.out.println("异常");
            System.err.println(e);
            System.exit(1);
        }
        while (flag) { // 死循环
            Socket socket = null;
            try {
                socket = server.accept();
                ServerThread cp = new ServerThread(socket, socket.getInetAddress().toString()); // 启动一个用户线程
                System.out.println("新进入一个用户");
                cp.setIndex(count + 1);
                Thread ct = new Thread(cp);
                ct.start();
                addConnection(socket, cp);
                count++;

            } catch (IOException e) {
                System.err.println(e);

                System.exit(1);
                try {
                    socket.close();
                } catch (IOException e1) {

                    e1.printStackTrace();
                }
            }
        }

    }

    public static Vector<ServerThread> getClients() {
        return clients;
    }

    public static void setClients(Vector<ServerThread> clients) {
        ChatServer.clients = clients;
    }

    public static Vector<Socket> getConnections() {
        return connections;
    }

    public static void setConnections(Vector<Socket> connections) {
        ChatServer.connections = connections;
    }

    public static int getCount() {
        return count;
    }

    public static void setCount(int count) {
        ChatServer.count = count;
    }

    public static ServerSocket getServer() {
        return server;
    }

    public static void setServer(ServerSocket server) {
        ChatServer.server = server;
    }
}
